<!--
数据
   projectUuid:"2c9fe31d79d0fba10179d0fea5be0000",
{
   db:"",//name
   table:"",//name
   field:""//name
}
-->

<template>
    <el-form>
        <el-form-item>
            <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
        </el-form-item>
        <el-form-item>
            <el-tree node-key="uuid" ref="selectTree" :data="treeList" default-expand-all :style="{maxHeight:maxHeight,overflowY:'scroll'}"
                        :filter-node-method="filterNode" :highlight-current="true"
                         @node-click="handleNodeClick" :props="defaultProps"></el-tree>
        </el-form-item>
    </el-form>
</template>

<script>
import request from '../utils/request';
export default {
    name: 'mc-db-table-field',
    data () {
        return {
            form:this.data,
            treeList:[],
            defaultProps: {
                children: 'children',
                label: 'name',
            },
            filterText:"",
            apiList:[],
        }
    },
    props:['data','projectUuid','maxHeight'],
    watch: {
      filterText(val) {
        this.$refs.selectTree.filter(val);
      }
    },
    mounted () {
       var _t = this;
       request.axios({$vue:_t,method:"get",url:"magical_lowcode/user/database/list",params:{projectUuid:_t.projectUuid}}).then(function(res) {
           _t.treeList = res.data;
           if(_t.form.db && _t.form.table && _t.form.field){
              _t.$nextTick(() => {
                 if(_t.treeList){
                     for(var i=0;i<_t.treeList.length;i++){
                         var db = _t.treeList[i];
                         if(db.name == _t.form.db){
                             var tables = db.children;
                             for(var j=0;j<tables.length;j++){
                                 var table = tables[j];
                                 if(table.name == _t.form.table){
                                       _t.$refs.selectTree.setCurrentKey(table.uuid);
                                       _t.clickCurrentNode();
                                 }
                             }
                         }
                     }

                 }
              })
           }
       }).catch(function (error) {
           console.log(error)
       });

    },
    methods:{
        filterNode(value, data) {
          if (!value) return true;
          return data.name.indexOf(value) !== -1;
        },
        clickCurrentNode:function(){
             var data = this.$refs.selectTree.getCurrentNode();
             var node = this.$refs.selectTree.getNode(data);
             this.handleNodeClick(data,node);
        },
        handleNodeClick:function(data,node){
            if(node.level==1){
                return;//数据库不用管
            }
            if(node.level==3){
                this.form.db = node.parent.parent.data.name;
                this.form.table = node.parent.data.name;
                this.form.field = data.fieldName;
                this.$emit("choose",this.form)
                //点击字段
                return ;
            }

            var databaseUuid = '';
            for(var i=0;i<this.treeList.length;i++){
                 var children = this.treeList[i].children;
                 if(children){
                      for(var j=0;j<children.length;j++){
                           if(children[j].uuid == data.uuid){
                             databaseUuid=this.treeList[i].uuid;
                             break;
                           }
                      }
                 }

            }
            var tableName = data.name;
            var _t = this;
            request.axios({$vue:_t,method:"get",url:"magical_lowcode/user/table/info",
                params:{projectUuid:_t.projectUuid,databaseUuid:databaseUuid,uuid:data.uuid}})
                .then(function(res) {
                var rootNode=res.data.data.rootNode;
                  if(!rootNode){
                    rootNode= MAGICAL_CODER_API.htmlToRootNode({html:res.data.data.html,pure:true});
                  }else{
                    rootNode = JSON.parse(rootNode);
                  }
                var tableInfo = _t.tableToFields(rootNode);
                var fields = tableInfo.fields;
                _t.expandTableFields(data,node,fields);
            }).catch(function (error) {
                console.log(error)
            });
        },
        /*平展字段*/
        expandTableFields(data,node,fields){
            this.$set(data, 'children', []);
            for(var i=0;i<fields.length;i++){
                var field = fields[i];
                data.children.push({uuid:data.uuid+field.name,name:field.title,fieldName:field.name})
            }
            if(this.form.field){
               this.$nextTick(() => {
                this.$refs.selectTree.setCurrentKey(data.uuid+this.form.field);
               });
            }
        },
        tableToFields:function(rootNode){
            var tableInfo = {};
            //字段信息
            var tableFields = [];//{name:"",type:"",len:2,defaultValue:"",pk:false,notNull:true,autoInc:false,comment:""}
            var children = rootNode.magicalCoder.children;
            if(children){
                for(var i=0;i<children.length;i++){
                    var field = {};
                    var elFormItem = children[i];
                    var attributes = elFormItem.attributes;
                    var magicalCoder = elFormItem.magicalCoder;
                    //注释
                    field.title = attributes.label;
                    {//寻找包含的控件
                        if(magicalCoder.children){
                            var controlNode = magicalCoder.children[0]
                            var controlAttributes = controlNode.attributes;
                            var controlMagicalCoder = controlNode.magicalCoder;
                            var tagName = controlMagicalCoder.tagName;
                            var vModel = controlAttributes['v-model'];
                            field.name = vModel;
                            if(!vModel){
                                field.name = controlAttributes[':data.sync'];
                            }
                             //检测是不是父子下拉框 父子下拉框 2个字段合并在一个组件了
                            if(tagName==='mc-parent-child-select'){
                                //检测父亲下拉框是否配置字段
                                var pmodel = controlAttributes[':p-model.sync'];
                                if(pmodel){
                                    var fieldParent = {name:pmodel};
                                    var parentJavaType = controlAttributes['mc-parent-java-type'];
                                    fieldParent.title = controlAttributes['mc-parent-comment'];
                                    if(controlAttributes['mc-child-comment']){
                                        field.title = controlAttributes['mc-child-comment'];
                                    }
                                    tableFields.push(fieldParent);
                                }
                            }else if(tagName==='mc-parent-child-grandson-select'){
                                 //检测父亲下拉框是否配置字段
                                var pmodel = controlAttributes[':p-model.sync'];
                                if(pmodel){
                                    var fieldParent = {name:pmodel};
                                    var parentJavaType = controlAttributes['mc-parent-java-type'];
                                    fieldParent.title = controlAttributes['mc-parent-comment'];
                                    if(controlAttributes['mc-child-comment']){
                                        field.title = controlAttributes['mc-child-comment'];
                                    }
                                    tableFields.push(fieldParent);
                                }
                                var cmodel = controlAttributes[':c-model.sync'];
                                if(cmodel){
                                    var fieldChild = {name:cmodel};
                                    var parentJavaType = controlAttributes['mc-child-java-type'];
                                    fieldChild.title = controlAttributes['mc-child-comment'];
                                    if(controlAttributes['mc-grandson-comment']){
                                        field.title = controlAttributes['mc-grandson-comment'];
                                    }
                                    tableFields.push(fieldChild);
                                }
                            }
                        }
                    }
                    tableFields.push(field);
                }
            }
            {
                for(var i=0; i<tableFields.length; i++){
                    for(var j=i+1; j<tableFields.length; j++){
                        if(tableFields[i].name==tableFields[j].name){         //第一个等同于第二个，splice方法删除第二个
                            tableFields.splice(j,1);
                            j--;
                        }
                    }
                }
            }
            tableInfo.fields = tableFields;
            return tableInfo;
        },
        changeApi:function(){
            this.$emit("choose",{stage:"api",apiUuid:this.form.apiUuid,fields:[]})
        },
        tabClick:function(){
            if(this.form.stage=='api'){
                this.changeApi();
            }else{
                this.clickCurrentNode();
            }
        }
    }
}
</script>

<style lang="scss">
.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: #409eff;
  color: white;
}
.el-tree-node.is-current
  > .el-tree-node__content {
  background-color: #409eff !important;
  color: white;
}
</style>
